﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
 
namespace MvcImproved.Generic.Controls
{
	interface INamedContainer
	{
		string Name
		{ get; set; }

		string Prefix
		{ get; set; }
	}

	public abstract class NamedGenericControl<TDataItem, TMemberValue> : GenericControl<TDataItem, TMemberValue>, INamedContainer
	{
		private static System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"[\[\]\.,]");
		protected NamedGenericControl(Func<TDataItem, TMemberValue> valueMember)
			: base(valueMember)
		{ }

		protected string _Name;
		protected string _PrefixedName;

		public string Prefix
		{
			get;
			set;
		}

		public bool AutoId
		{ get; set; }

		public string CalculatedName(string name)
		{
			string parentedPrefix = null;
			string indexedSuffix = "";

			Control parent = this.Parent;
			while (parent != null)
			{
				INamedContainer namedContainer = parent as INamedContainer;
				IArrayIndexed indexedContainer = parent as IArrayIndexed;
				if (namedContainer != null)
				{
					if (!String.IsNullOrEmpty(namedContainer.Name))
						parentedPrefix = namedContainer.Name;
					break;
				}
				// We only care about IArrayIndexed if it's not a parent of a namedContainer
				if (indexedContainer != null)
					indexedSuffix = indexedContainer.IndexSuffix;

				parent = parent.Parent;
			}
			if (Prefix != null)
				parentedPrefix = Prefix + indexedSuffix;
			else if (parentedPrefix != null)
				parentedPrefix = parentedPrefix + indexedSuffix + '.' + name;
			else
				parentedPrefix = name + indexedSuffix;

			return parentedPrefix;
		}

		public virtual string Name
		{
			get
			{
				if (_Name == null)
					_Name = CalculatedName(PrefixedName);
				return _Name;
			}
			set
			{
				_Name = value;
			}
		}

		public virtual string PrefixedName
		{
			get { return _PrefixedName ?? ValueMember; }
			set { _PrefixedName = value; }
		}

		private string _ID;
		public override string ClientID
		{
			get
			{
				if ((_ID == null) && AutoId)
					_ID = _Regex.Replace(Name, "_");
				return _ID ?? base.ID;
			}
		}
	}
}
